package cn.itcast.bos.service.impl;

import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Predicates;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.repository.CourierRepository;
import cn.itcast.bos.service.CourierService;

@Service
@Transactional
public class CourierServiceImpl implements CourierService {
	
	@Autowired
	private CourierRepository courierRepository;
	
	@Override
	public void save(Courier courier) {
		courierRepository.save(courier);
	}
	/**
	 * 无条件分页查询
	 * */
	@Override
	public Page<Courier> findPageData(Pageable pageable) {
		return courierRepository.findAll(pageable);
	}
	/**
	 * 有条件分页查询
	 * */
	@Override
	public Page<Courier> findPageDataCification(Specification<Courier> specification,Pageable pageable) {
		return courierRepository.findAll(specification, pageable);
	}
	
	/**
	 * 作废Courier
	 * */
	@Override
	public void deleteCourier(String[] idsArray) {
		for (String id : idsArray) {
			courierRepository.updateDelTag(Integer.parseInt(id));
		}
		
	}
	/**
	 * 还原Courier
	 * */
	@Override
	public void restoreCourier(String[] idsArray) {
		for (String id : idsArray) {
			courierRepository.updateDelTagAdd(Integer.parseInt(id));
		}
	}
	
	/**
	 * 查询没有被关联的快递员
	 * @return 
	 * */
	@Override
	public List<Courier> findnoassociation() {
		// 封装Specification，查询没有被关联定区的快递员，即fixedAreas的集合字段为null
		Specification<Courier> specification = new Specification<Courier>() {
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				//isEmpty   判断是否为空
				Predicate predicate = cb.isEmpty(root.get("fixedAreas").as(Set.class));
				return predicate;
			}
		};
		
		return courierRepository.findAll(specification);
	}
	@Override
	public List<Courier> findByFixedAreaId(String fixedAreaId) {
		return courierRepository.findByFixedAreaId(fixedAreaId);
	}

}
